/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Project: javase2203 - Demo04
 * <p>Powered by webrx On 2022-07-12 17:00:06
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Demo04 {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final synchronized int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 10 ? 0 : current + 1;
        }while (!this.atomicInteger.compareAndSet(current, next));
        String tn = Thread.currentThread().getName();
        System.out.println(tn+":访问次数：" + next);
        try{
            TimeUnit.SECONDS.sleep(1);
        }catch(Exception e){
            e.printStackTrace();
        }
        return next;
    }

    public static void main(String[] args) {
        var d = new Demo04();
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(d::getAndIncrement,"t"+i);

            t.start();
        }


    }
}
